﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using popLib;
using popLib.ExtensionClass;
using PhotoMgr.src.common;
using PhotoMgr.src.database;
using System.Threading;
using System.IO;

namespace PhotoMgr.src.gui.photo
{
    public partial class MarkerForm : Form
    {
        SocketClient client;
        View_RoundImage currentImage;
        Contest contest;
        Round round;
        List<View_ContestUserSetting> settings;
        int DelayTime = 0;
        int CurrentTime = 0;
        ScoreType CurrentScoreType;

        public MarkerForm()
        {
            InitializeComponent();
            this.Icon = PhotoMgr.Properties.Resources.logo32;


            Login loginForm = new Login();
            loginForm.ShowDialog();
            if (loginForm.DialogResult != System.Windows.Forms.DialogResult.OK)
            {
                this.Opacity = 0;
                FormLib.ExitTimer(this, 100);
                return;
            }

            lbl_info.Text = string.Format("Người dùng: {0}({1})", UserAccount.Instance.Fullname, UserAccount.Instance.Username);

            ResetForm();
        }

        void client_ReceiveMessageEvent(string message)
        {
            ThreadStart ts = delegate {
                string[] items = message.Split(';');
                switch (items[0])
                {
                    case "VIEW":
                        ViewImage(items);
                        break;
                    case "LOGIN":
                        client.SendMessage("LOGIN;" + UserAccount.Instance.Username + ";" + UserAccount.Instance.UserID);
                        break;
                    case "ACCEPTED":
                        int contestID = NumberLib.getInt(items[1]);
                        int roundID = NumberLib.getInt(items[2]);
                        int scoreType = NumberLib.getInt(items[3]);
                        CurrentScoreType = (ScoreType)scoreType;

                        contest = DBManager.Detail_Contest(contestID);
                        round = DBManager.Detail_Round(roundID);
                        settings = DBManager.Contest_GetContestUserSetting(contestID);
                        

                        btn_start.Enabled = false;

                        CurrentTime = DelayTime = (int)settings[0].DelayTime;

                        string[] marks = settings[0].MaxScore.SplitByAny(",;|");
                        cbx_mark.Items.Clear();
                        cbx_mark.Items.AddRange(marks);

                        lbl_title.Text = contest.ContestName;
                        this.Text = contest.ContestName + " - Vòng " + round.RoundLevel + "- [QSV:" + UserAccount.Instance.Fullname + "]";

                        LockForm(true, "Xin vui lòng đợi quan sát viên bắt đầu!!!", true);
                        break;
                    case "REJECT":
                        client.AutoReconnect = false;
                        FormLib.alert("Tài khoản của bạn không được phép chấm cho cuộc thi này.\r\nXin vui lòng liên hệ ban tổ chức!!!");
                        client.Stop();                        
                        this.Close();
                        break;
                    case "PAUSE":
                        LockForm(true, "Quan sát viên đang tạm ngưng.\r\nXin vui lòng đợi!!!", false);
                        break;
                    case "END":
                        LockForm(true, "Vòng chấm thi đã kết thúc.\r\nXin vui lòng đợi!!!", true);
                        ResetForm();
                        break;
                    case "START":
                        LockForm(false, "", false);
                        break;
                    case "SAVESCORE":
                        SaveScore();
                        break;
                }
            };
            if (this != null) this.Invoke(ts);
        }



        void client_ConnectionStatusChangedEvent(bool isConnected)
        {
            if (!isConnected)
            {
                ThreadStart ts = delegate
                {
                    LockForm(true, "Mất kết nối với máy chủ. \r\nXin vui lòng kết nối lại với máy chủ!!!", true);
                    ResetForm();
                };
                if( this != null )
                    this.Invoke(ts);
            }
        }
               
        void ViewImage(string[] items)
        {
            int roundImageID = NumberLib.getInt(items[1]);
            currentImage = DBManager.RoundImage_GetByRoundImageID(roundImageID, UserAccount.Instance.UserID);
            
            lbl_imageTitle.Text = currentImage.ImageTitle;
            lbl_artistName.Text = "Tác giả: " + currentImage.ArtistName;
            lbl_note.Text = "";

            string file = Path.Combine(Configuration.Instance.ServerPath, currentImage.ImagePath);
            System.Drawing.Image image = System.Drawing.Image.FromFile(file);
            pbx_image.Image = image;
            pbx_image.SizeMode = PictureBoxSizeMode.Zoom;


            LockForm(false, "", true);

            double score = (double)currentImage.Score;
            if( CurrentScoreType == ScoreType.SubScore ) score = (double)currentImage.SubScore;
            if( CurrentScoreType == ScoreType.ThirdScore ) score = (double)currentImage.ThirdScore;

            if (score > 0)
            {
                cbx_mark.Text = score.ToString();
            }
            else
            {
                cbx_mark.SelectedIndex = -1;
                btn_continue.Enabled = false;
            }            

            startTimer();

            GC.Collect();
        }

        void SaveScore()
        {
            DBManager.ImageScore_SaveScore(currentImage.RoundImageID, UserAccount.Instance.UserID, NumberLib.getDouble(cbx_mark.Text), "S", CurrentScoreType);
        }
                

        private void btn_next_Click(object sender, EventArgs e)
        {
            client.SendMessage("UPDATE");
            SaveScore();
            LockForm(true, "Xin vui lòng đợi hình tiếp theo!!!", true);
        }

        private void btn_start_Click(object sender, EventArgs e)
        {
            client.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            CurrentTime--;
            ts_progessbar.Value = NumberLib.getInt(NumberLib.getDouble(CurrentTime)/( NumberLib.getDouble(DelayTime) /100) );            

            if (CurrentTime <= 0)
            {
                CurrentTime = DelayTime;
                timer1.Stop();
                LockForm(true, "Xin vui lòng đợi hình tiếp theo!!!", true);
            }
        }

        void startTimer()
        {
            timer1.Start();
            CurrentTime = DelayTime;
        }

        void LockForm(bool isLock = true, string message = "Xin vui lòng đợi hình tiếp theo!!!", bool isResetTimer = false)
        {
            btn_continue.Enabled = !isLock;
            cbx_mark.Enabled = !isLock;

            if (isLock)
            {
                FormLib.showAnimatedLoading(this, message, false);
                timer1.Stop();
            }
            else
            {
                FormLib.hideLoading(this);
            }

            if (isResetTimer)
            {
                ts_progessbar.Value = 0;                
            }
        }

        private void cbx_mark_SelectedIndexChanged(object sender, EventArgs e)
        {
            btn_continue.Enabled = cbx_mark.SelectedIndex >= 0;
        }

        private void MarkerForm_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F4) btn_continue.PerformClick();
            if (e.KeyCode == Keys.F5) btn_start.PerformClick();
        }

        void ResetForm()
        {
            client = new SocketClient(FormLib.getAppSettingINI("setting", "ServerIP", "127.0.0.1"), 9889);
            client.WriteLog = false;
            client.ConnectionStatusChangedEvent += new SocketClient.ConnectionStatusChanged(client_ConnectionStatusChangedEvent);
            client.ReceiveMessageEvent += new SocketClient.ReceiveMessage(client_ReceiveMessageEvent);

            
            pbx_image.Image = null;
            lbl_imageTitle.Text = "";
            lbl_artistName.Text = "";
            lbl_note.Text = "";

            btn_continue.Enabled = false;
            btn_start.Enabled = true;
            cbx_mark.Enabled = false;
        }
    }
}